/*
 * EnigmaGM - A feature rich guild management system.
 * Copyright (C) 2007 ajiaojr.
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
package org.ajiaojr.enigmagm.client.dialog;

import org.ajiaojr.enigmagm.client.Paged;
import org.ajiaojr.enigmagm.client.SortablePaged;
import org.ajiaojr.enigmagm.client.data.Event;
import org.ajiaojr.enigmagm.client.data.Purchase;
import org.ajiaojr.enigmagm.client.service.CharacterService;
import org.ajiaojr.enigmagm.client.service.CharacterServiceAsync;
import org.ajiaojr.enigmagm.client.service.PurchaseService;
import org.ajiaojr.enigmagm.client.service.PurchaseServiceAsync;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.SourcesTabEvents;
import com.google.gwt.user.client.ui.SourcesTableEvents;
import com.google.gwt.user.client.ui.TabListener;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TableListener;
import com.google.gwt.user.client.ui.VerticalPanel;

import java.util.List;

/**
 * Displays event details.
 * 
 * @author ajiaojr
 */
public class EventDetailsDialog extends DialogBox {

  private class AttendeesGrid extends Paged {
    public static final int MAX_RESULTS = 40;

    public AttendeesGrid(Panel parent) {
      super(parent, MAX_RESULTS);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.ajiaojr.enigmagm.client.Paged#populate()
     */
    public void populate() {
      CharacterServiceAsync eventService = CharacterService.Util.getInstance();

      eventService.findAttendees(event.getEventID(), firstResult, maxResults,
          new AsyncCallback() {

            public void onFailure(Throwable caught) {
              Window.alert(caught.getMessage());
            }

            public void onSuccess(Object result) {
              panel.clear();

              final List attendees = (List) result;

              int rows = attendees.size() / 5;

              if (attendees.size() % 5 > 0) {
                rows++;
              }

              Grid grid = new Grid(rows, 5);

              grid.setWidth("100%");
              grid.setStyleName("gwt-table");
              grid.getColumnFormatter().setWidth(0, "20%");
              grid.getColumnFormatter().setWidth(1, "20%");
              grid.getColumnFormatter().setWidth(2, "20%");
              grid.getColumnFormatter().setWidth(3, "20%");
              grid.getColumnFormatter().setWidth(4, "20%");
              grid.addTableListener(new TableListener() {

                public void onCellClicked(SourcesTableEvents sender, int row,
                    int cell) {
                  org.ajiaojr.enigmagm.client.data.Character r =
                      (org.ajiaojr.enigmagm.client.data.Character) attendees
                          .get(row * 5 + cell);
                  CharacterDetailsDialog rdd = new CharacterDetailsDialog(r);
                  hide();
                  rdd.show();
                }
              });

              for (int i = 0; i < rows; i++) {
                for (int j = 0; j < 5 && i * 5 + j < attendees.size(); j++) {
                  grid.setText(i, j,
                      ((org.ajiaojr.enigmagm.client.data.Character) attendees
                          .get(i * 5 + j)).getCharacterName());
                  grid.getCellFormatter().addStyleName(i, j, "clickable");
                }
              }
              panel.add(grid);
            }
          });
    }
  }

  private class PurchasesGrid extends SortablePaged {
    public static final int MAX_RESULTS = 20;

    public PurchasesGrid(Panel parent) {
      super(parent, MAX_RESULTS, "character_name");
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.ajiaojr.enigmagm.client.Paged#populate()
     */
    public void populate() {
      PurchaseServiceAsync purchaseService = PurchaseService.Util.getInstance();

      purchaseService.findByEventID(event.getEventID(), sortAttribute,
          ascending, firstResult, maxResults, new AsyncCallback() {

            public void onFailure(Throwable caught) {
              Window.alert(caught.getMessage());
            }

            public void onSuccess(Object result) {
              panel.clear();

              final List points = (List) result;
              int purchasesCount = points.size();

              Grid grid = new Grid(purchasesCount + 1, 2);
              grid.setWidth("100%");
              grid.setStyleName("gwt-table");
              grid.addStyleName("dataTable");
              grid.setText(0, 0, "Character Name");
              grid.setText(0, 1, "Item Name");
              grid.getRowFormatter().addStyleName(0, "header");
              grid.getRowFormatter().addStyleName(0, "clickable");
              grid.getColumnFormatter().setWidth(0, "140px");
              grid.addTableListener(new TableListener() {
                public void onCellClicked(SourcesTableEvents sender, int row,
                    int cell) {
                  if (row == 0) {
                    switch (cell) {
                      case 0:
                        setSortAttribute("character_name");
                        break;
                      case 1:
                        setSortAttribute("item_name");
                        break;
                    }
                  }
                }
              });

              for (int i = 0; i < purchasesCount; i++) {
                Purchase purchase = (Purchase) points.get(i);

                int currentRow = i + 1;
                grid.setText(currentRow, 0, purchase.getCharacterName());
                grid.setText(currentRow, 1, purchase.getItemName());
                grid.getRowFormatter().addStyleName(currentRow, "highlight");
              }

              panel.add(grid);
              attachNavBar();
            }
          });
    }
  }

  private AttendeesGrid attendeesGrid;

  private Event event;

  private PurchasesGrid purchasesGrid;

  public EventDetailsDialog(Event event) {
    super(true);
    this.event = event;
    init();
  }

  public Event getEvent() {
    return event;
  }

  public void setEvent(Event event) {
    this.event = event;
  }

  private void init() {
    setHTML("Event Details");

    final VerticalPanel verticalPanel = new VerticalPanel();
    setWidget(verticalPanel);
    verticalPanel.setSize("500px", "100%");

    final TabPanel tabPanel = new TabPanel();
    verticalPanel.add(tabPanel);

    tabPanel.addTabListener(new TabListener() {
      public boolean onBeforeTabSelected(SourcesTabEvents sender, int tabIndex) {
        return true;
      }

      public void onTabSelected(SourcesTabEvents sender, int tabIndex) {
        switch (tabIndex) {
          case 0:
            attendeesGrid.populate();
            break;
          case 1:
            purchasesGrid.populate();
            break;
        }
      }
    });

    tabPanel.setWidth("100%");

    final VerticalPanel attendeesPanel = new VerticalPanel();
    tabPanel.add(attendeesPanel, "Attendees");
    attendeesPanel.setStyleName("gwt-TabBody");
    attendeesPanel.setSpacing(5);

    final VerticalPanel verticalPanel_1 = new VerticalPanel();
    attendeesPanel.add(verticalPanel_1);
    verticalPanel_1.setWidth("100%");
    attendeesGrid = new AttendeesGrid(verticalPanel_1);

    /*
     * TableViewer attendeesViewer = new TableViewer();
     * verticalPanel_1.add(attendeesViewer.getWidget()); ContentProvider
     * attendeesProvider = new ContentProvider() { public void
     * inputChanged(Object input) { TableContentProviderInput currentInput =
     * (TableContentProviderInput) input;
     * AttendanceService.Util.getInstance().findByEventID(event.getEventID(),
     * currentInput.getFirstResult(), currentInput.getMaxResults(), new
     * AsyncCallback() { public void onFailure(Throwable caught) {
     * Window.alert(caught.getMessage()); } public void onSuccess(Object result) {
     * contentListeners.fireContentChangedEvent(((List) result) .toArray()); }
     * }); } }; attendeesViewer.setContentProvider(attendeesProvider); // TODO
     * should be getting info from DB instead of hard coded
     * attendeesViewer.addColumn("Druid", null);
     * attendeesViewer.addColumn("Hunter", null);
     * attendeesViewer.addColumn("Mage", null);
     * attendeesViewer.addColumn("Paladin", null);
     * attendeesViewer.addColumn("Priest", null);
     * attendeesViewer.addColumn("Rogue", null);
     * attendeesViewer.addColumn("Shaman", null);
     * attendeesViewer.addColumn("Warlock", null);
     * attendeesViewer.addColumn("Warrior", null);
     * attendeesViewer.addColumn("Noob", null);
     * attendeesViewer.setTableLabelProvider(new TableLabelProvider() { public
     * String getLabel(Object object, int column) {
     * org.ajiaojr.enigmagm.client.data.Character c =
     * (org.ajiaojr.enigmagm.client.data.Character) object; switch (column) {
     * case 0: return c.getCharacterClass().equals("Druid") ?
     * c.getCharacterName() : null; case 1: return
     * c.getCharacterClass().equals("Hunter") ? c .getCharacterName() : null;
     * case 2: return c.getCharacterClass().equals("Mage") ?
     * c.getCharacterName() : null; case 3: return
     * c.getCharacterClass().equals("Paladin") ? c .getCharacterName() : null;
     * case 4: return c.getCharacterClass().equals("Priest") ? c
     * .getCharacterName() : null; case 5: return
     * c.getCharacterClass().equals("Rogue") ? c.getCharacterName() : null; case
     * 6: return c.getCharacterClass().equals("Shaman") ? c .getCharacterName() :
     * null; case 7: return c.getCharacterClass().equals("Warlock") ? c
     * .getCharacterName() : null; case 8: return
     * c.getCharacterClass().equals("Warrior") ? c .getCharacterName() : null;
     * case 9: return c.getCharacterClass().equals("Noob") ?
     * c.getCharacterName() : null; default: return null; } } });
     * attendeesViewer.setInput(new TableContentProviderInput(0, 40));
     */

    final VerticalPanel purchasesPanel = new VerticalPanel();
    tabPanel.add(purchasesPanel, "Item Purchases");
    purchasesPanel.setStyleName("gwt-TabBody");
    purchasesPanel.setSpacing(5);

    final VerticalPanel verticalPanel_2 = new VerticalPanel();
    purchasesPanel.add(verticalPanel_2);
    verticalPanel_2.setWidth("100%");
    purchasesGrid = new PurchasesGrid(verticalPanel_2);
    tabPanel.selectTab(0);

    setPopupPosition((Window.getClientWidth() - 500) / 2, (Window
        .getClientHeight() - 300) / 2);
  }
}
